﻿package com.calefk.util {

	public class TimerCustom {
		
		private var mCurrentTime:int;
		private var mCurrentLoop:int;
		private var mOldtime:int;
		
		private var mTimeFinish:int;
		private var mLoop:int;
		private var mFunctionExecute:Function;
		
		private static const ST_START:int = 0;
		private static const ST_STOP:int = 1;
		private var mState:int;
		
		public function get isStop():Boolean { return (mState == ST_STOP); }
		
		public function TimerCustom(functionExecute:Function, loop:int = 0 , timeFinish:int = 1000) {
			mCurrentLoop = 0;
			mLoop = loop;
			mTimeFinish = timeFinish;
			mFunctionExecute = functionExecute;
			mState = ST_STOP;
		}
		
		public function start():void {
			mOldtime = mCurrentTime;
			mState = ST_START;
		}
		
		public function stop():void {
			mState = ST_STOP;
		}
		
		public function reset():void {
			mCurrentLoop = 0;
			mOldtime = mCurrentTime;
			mState = ST_START;
		}
		
		public function update(dt:int) {
			mCurrentTime += dt;
			switch (mState) {
				case ST_START:
					if ((mLoop == 0) || (mCurrentLoop < mLoop && mLoop != 0)) {
						var t:int = mCurrentTime - mOldtime;
						if (t >=  mTimeFinish) {
							mCurrentLoop++;
							// reset values
							mOldtime = mCurrentTime;
                            // call function
                            mFunctionExecute();
						}
					} else {
						mState = ST_STOP;
					}
					break;
				case ST_STOP:
					break;
			}
		}
		
		public function clean():void {
			mFunctionExecute = null;
		}
	}

}